import VueRouter from "vue-router";
import Cookie from 'js-cookie'

//导入组件
// import Index from '../components/Index'
import Main from '../views/Main'
import Home from '../views/Home'
import User from '../views/User'
import AnimeItem from '../views/animeManage/AnimeItem'
import Login from '../views/Login'
import PartyMain from '../views/partys/PartyMain'
import PartyAdd from '../views/partys/PartyAdd'
import ArticleMain from '../views/articleManage/ArticleMain'

const router=new VueRouter({
    mode:'hash',
    routes:[
        {
            path:'/',component:Main,redirect:'/home',
            children:[
                {path:'home',name:'home',meta:{isAuth:true},component:Home},
                {path:'user',name:'user',meta:{isAuth:true},component:User},
                {path:'chinese',name:'chinese',meta:{isAuth:true},component:AnimeItem},
                {path:'japanese',name:'japanese',meta:{isAuth:true},component:AnimeItem},
                {path:'other',name:'other',meta:{isAuth:true},component:AnimeItem},
                {path:'partyMain',name:'partyMain',meta:{isAuth:true},component:PartyMain},
                {path:'partyAdd',name:'partyAdd',meta:{isAuth:true},component:PartyAdd},
                {path:'articleMain',name:'articleMain',meta:{isAuth:true},component:ArticleMain},
            ]
        },
        {
          path:'/login',name:'login',component:Login,
        },
    ]
})
/*
  针对路由push  重复点击报错解决方案
*/
const originPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
  // 判断token是否存在
  const token = localStorage.getItem('token')
  // token不存在，说明当前用户是未登录，应该跳转至登录页
  if (!token && to.meta.isAuth === true) {
    next({ name: 'login' })
  } else if (token && to.name === 'login') {//有token了，不能进入登录页。返回原来的页
    next({ name: from.name })
  } else {//其他情况。有token，跳转的不是登录页，放行
    next()
  }
})

export default router